package site.kitcheng.springboottest.infra.config.sql;

import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.*;
import java.sql.Connection;

import java.util.Properties;

/**
 * ClassName: MybatisPlusInterceptor
 * Package: site.kitcheng.springboottest.infra.config.sql
 * Description:
 *
 * @Author jiangCheng
 * @Create 2025/3/21 10:01
 * @Version 1.0
 */

@Intercepts({
        @Signature(
                type = StatementHandler.class, // 指定拦截的 MyBatis 组件
                method = "prepare",            // 需要拦截的方法
                args = {Connection.class, Integer.class} // 该方法的参数
        )
})
public class MyBatisSqlInterceptor implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        // 获取 StatementHandler
        StatementHandler statementHandler = (StatementHandler) invocation.getTarget();

        // 获取 SQL
        String sql = statementHandler.getBoundSql().getSql();
        System.out.println("拦截到 SQL: " + sql);

        // TODO: 可以在这里修改 SQL 语句，比如添加权限过滤

        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        // 包装目标对象，生成代理
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        // 这里可以读取配置参数
    }
}
